import java.util.*;

public class MyTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //public TreeNode root;
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        E.right = H;
        C.left = F;
        C.right = G;
        return A;
    }

    //前序遍历
    public List<Character> preOrder(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        list.add(root.val);
        List<Character> leftTree = preOrder(root.left);
        list.addAll(leftTree);
        List<Character> rightTree = preOrder(root.right);
        list.addAll(rightTree);
        return list;
    }

    //中序遍历
    public List<Character> inOrder(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        List<Character> leftTree = inOrder(root.left);
        list.addAll(leftTree);
        list.add(root.val);
        List<Character> rightTree = inOrder(root.right);
        list.addAll(rightTree);
        return list;
    }

    //后序遍历
    public List<Character> postOrder(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        List<Character> leftTree = postOrder(root.left);
        list.addAll(leftTree);
        List<Character> rightTree = postOrder(root.right);
        list.addAll(rightTree);
        list.add(root.val);
        return list;
    }

    //获取树中节点的个数
    public int size(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return size(root.left) + size(root.right) + 1;
    }

    //获取树节点个数（遍历思想）
    public int nodeSize;

    public void size1(TreeNode root) {
        if (root == null) {
            return;
        }
        nodeSize++;
        size1(root.left);
        size1(root.right);
    }

    //获取叶子节点的个数
    public int getLeafNodeCount(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
    }

    public int leafSize;

    //获取叶子节点个数（遍历思路）
    public void getLeafNodeCount1(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    //获取第K层节点的个数
        public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }

    //获取二叉树的高度
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHigh = getHeight(root.left);
        int rightHigh = getHeight(root.right);
        if (leftHigh > rightHigh) {
            return leftHigh + 1;
        } else {
            return rightHigh + 1;
        }
    }

    //检测元素是否存在
    public TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        } else {
            TreeNode leftRoot = find(root.left, val);
            if (leftRoot != null) {
                return leftRoot;
            }
            TreeNode rightRoot = find(root.right, val);
            if (rightRoot != null) {
                return rightRoot;
            }
        }
        return null;
    }

    //判断二叉树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q != null || p != null && q == null) {
            return false;
        }
        if (p == null && q == null) {
            return true;
        }
        if (p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    //另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return false;
        }
        if (isSameTree(root, subRoot)) {
            return true;
        }
        if (isSameTree(root.left, subRoot)) {
            return true;
        }
        if (isSameTree(root.right, subRoot)) {
            return true;
        }
        return false;
    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    //判断一个二叉树是否为平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return Math.abs(leftH - rightH) < 2 && isBalanced(root.left) && isBalanced(root.right);
    }

    public boolean isBalanced1(TreeNode root) {
        return getHeight1(root) >= 0;
    }

    public int getHeight1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHigh = getHeight(root.left);
        int rightHigh = getHeight(root.right);
        if (leftHigh > 0 && rightHigh > 0 && Math.abs(leftHigh - rightHigh) <= 1) {
            return Math.max(leftHigh, rightHigh) + 1;
        } else {
            return -1;
        }
    }

    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if (leftTree != null && rightTree == null || leftTree == null && rightTree != null) {
            return false;
        }
        if (leftTree == null && rightTree == null) {
            return true;
        }
        if (leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.right, rightTree.left) && isSymmetricChild(leftTree.left, rightTree.right);
    }

    //二叉树的层序遍历
    public void levelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    public List<List<Character>> levelOrder1(TreeNode root) {
        List<List<Character>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int ret = queue.size();
            List<Character> list1 = new ArrayList<>();
            while (ret != 0) {
                TreeNode cur = queue.poll();
                list1.add(cur.val);
                ret--;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            list.add(list1);
        }
        return list;
    }

    //找到两个指定节点的公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode leftRet = lowestCommonAncestor(root.left, p, q);
        TreeNode rightRet = lowestCommonAncestor(root.right, p, q);
        if (leftRet != null && rightRet != null) {
            return root;
        } else if (leftRet != null) {
            return leftRet;
        } else if (rightRet != null) {
            return rightRet;
        }
        return null;
    }

    //非递归方法找公共祖先
    public boolean find(TreeNode root, TreeNode node, Deque<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean leftRet = find(root.left, node, stack);
        if (leftRet == true) {
            return true;
        }
        boolean rightRet = find(root.right, node, stack);
        if (rightRet == true) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        Deque<TreeNode> stack1 = new LinkedList<>();
        find(root, p, stack1);
        Deque<TreeNode> stack2 = new LinkedList<>();
        find(root, q, stack2);
        if (stack1.size() > stack2.size()) {
            int size = stack1.size() - stack2.size();
            while (size != 0) {
                stack1.pop();
                size--;
            }
        } else {
            int size = stack2.size() - stack1.size();
            stack2.pop();
            size--;
        }
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            if (stack1.peek() != stack2.peek()) {
                stack1.pop();
                stack2.pop();
            } else {
                return stack1.peek();
            }
        }
        return null;
    }

    //根据一颗树的前序遍历于中序遍历构造二叉树
    public int i = 0;

    public TreeNode buildTree(char[] preorder, char[] inorder) {
        int begin = 0;
        int end = inorder.length - 1;
        return buildChildTree(preorder, inorder, begin, end);
    }

    public TreeNode buildChildTree(char[] preorder, char[] inorder, int begin, int end) {
        if (begin > end) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[i]);
        int index = findIndex(inorder, begin, end, preorder[i]);
        i++;
        root.left = buildChildTree(preorder, inorder, begin, index - 1);
        root.right = buildChildTree(preorder, inorder, index + 1, end);
        return root;
    }

    public int findIndex(char[] inorder, int begin, int end, int key) {
        for (int i = begin; i <= end; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

    //二叉树创建字符串
    public String tree2str(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root, stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root, StringBuilder stringBuilder) {
        if (root == null) {
            return;
        }
        stringBuilder.append(root.val);
        if (root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left, stringBuilder);
            stringBuilder.append(")");
        } else {
            if (root.right != null) {
                stringBuilder.append("()");
            } else {
                return;
            }
        }
        if (root.right == null) {
            return;
        } else {
            stringBuilder.append("(");
            tree2strChild(root.right, stringBuilder);
            stringBuilder.append(")");
        }
    }

    //判断一个二叉树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.peek() != null) {
            TreeNode cur = queue.poll();
            queue.offer(cur.left);
            queue.offer(cur.right);
        }
        while (!queue.isEmpty()) {
            if (queue.poll() != null) {
                return false;
            }
        }
        return true;
    }

    //二叉树前序非递归遍历实现
    public void preOrderNor(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()){
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
        TreeNode top = stack.pop();
        cur = top.right;
    }
}
    //二叉树中序非递归遍历实现
        public void inOrderNor(TreeNode root){
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()){
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }

    //二叉树后续非递归遍历实现
    public void postOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null || !stack.isEmpty()){
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            if (top.right == null || top.right == pre) {
                System.out.print(top.val + " ");
                stack.pop();
                pre = top;
            }
            else {
                cur = top.right;
            }
        }
        System.out.println();
    }

    //二叉树的宽度
    public int widthOfBinaryTree(TreeNode root){
        Deque<Node> deque = new LinkedList<>();
        int ans = 1;
        deque.add(new Node(root, 0));

        while (!deque.isEmpty()){
            int size = deque.size();
            int wide = deque.peekLast().id - deque.peekFirst().id + 1;
             ans = Math.max(ans, wide);
            for (int i = 0; i < size; i++){
                 Node node = deque.poll();
                TreeNode treeNode = node.treeNode;
                 int id = node.id;
                 if (treeNode.left != null){
                     deque.add(new Node(treeNode.left, id * 2 + 1));
                 }
                 if (treeNode.right != null){
                     deque.add(new Node(treeNode.right, id * 2 + 2));
                 }
            }
        }
        return ans;
    }
    class Node{
        TreeNode treeNode;
        int id;

        public Node(TreeNode treeNode, int id){
            this.treeNode = treeNode;
            this.id = id;
        }
    }
    //把二叉搜素树转成有序双向链表
    TreeNode head = null;
    TreeNode prev = null;
    public TreeNode treeToDoublyList(TreeNode root) {
        if (root == null){
            return null;
        }
        func(root);
        head.left = prev;
        prev.left = head;
        return head;
    }
    public void func(TreeNode cur){
        if (cur == null){
            return;
        }
        func(cur.left);
        if (prev != null){
            prev.right = cur;
        }
        else {
            head = cur;
        }
        cur.left = prev;
        prev = cur;
        func(cur.right);
    }

    //递增顺序搜索树
    List<Character> array = new ArrayList<>();
    public TreeNode increasingBST(TreeNode root) {
        if (root == null){
            return null;
        }
        fun(root);
        TreeNode head = new TreeNode('s');
        TreeNode cur = head;
        for (char x : array) {
            cur.right = new TreeNode(x);
            cur = cur.right;
        }
        return head.right;
    }

    //遍历一个二叉树
    public void fun(TreeNode root){
        if (root == null){
            return;
        }
        fun(root.left);
        array.add(root.val);
        fun(root.right);
    }

    //合并二叉树
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null){
            return root2;
        }
        if (root2 == null){
            return root1;
        }
        //TreeNode merge = new TreeNode(root1.val + root2.val);
        //merge.left = mergeTrees(root1.left, root2.left);
        //merge.right = mergeTrees(root1.right, root2.right);
        //return merge;
        return root1;
    }

    //把二叉搜索树转化为累加树
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root != null){
            convertBST(root.right);
            sum += root.val;
            //root.val = sum;
            convertBST(root.left);
        }
        return root;
    }
























}
